import * as fs from "fs";
import * as path from "path";
import * as Minio from "minio";
const OSS = require("ali-oss");
require("dotenv").config();

// 创建 OSS 客户端实例
const ossClient = new OSS({
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  bucket: process.env.OSS_bucket,
  region: process.env.OSS_region, 
});

// 创建 MinIO 客户端实例
const minioClient = new Minio.Client({
  endPoint: "localhost",
  port: 9000,
  useSSL: false,
  accessKey: "q8ewY1JhHDpYXbxhDwwo",
  secretKey: "FnV4Kofnv2d3qZ397PGIBgLeV35nJPt4GSzrY1t7",
});

//保持OSS的目录结构和MinIO的目录结构一致
const minioBucket: any = process.env.OSS_bucket;
// 创建 MinIO 存储桶
minioClient.bucketExists(minioBucket, function (err: any, exists: any) {
  if (err) {
    console.log("Error checking bucket exists", err);
    return;
  }
  if (exists) {
    console.log("Bucket already exists");
  } else {
    console.log("Creating bucket", minioBucket);
    minioClient.makeBucket(minioBucket)
    }
  })


async function downloadFilesFromOSS(
  ossClient: typeof OSS,
  bucketName: any,
  folderName: string,
  localFolderPath: string
): Promise<void> {
  try {
    const result = await ossClient.list({
      bucket: process.env.OSS_bucket,
      prefix: "toubao/content/备忘",
    });
    const metaData = {
      "Content-Type": "application/json",
    };
    console.log(result);
    // 遍历文件和文件夹
    for (const object of result.objects) {
      const objectKey = object.name;
      const objectPath = path.join(
        localFolderPath,
        objectKey.replace(folderName, "")
      );
      const objectDir = path.dirname(objectPath);
      // 确保本地目录存在
      if (!fs.existsSync(objectDir)) {
        fs.mkdirSync(objectDir, { recursive: true });
      }
      //筛选条件,通过判断objects里的storageClass（存储类型）或者size（大小）来筛选文件
      if (object.size <= 40000) {
        // 下载文件
        await ossClient.get(objectKey, fs.createWriteStream(objectPath));
        console.log(`文件 ${objectKey} 下载完成`);

        // 上传文件到 MinIO
        await minioClient.fPutObject(minioBucket, objectKey, objectPath,metaData);
        console.log(`文件 ${objectKey} 上传完成`);
      }
    }
  } catch (error) {
    console.error("下载文件时出错:", error);
  }
}
downloadFilesFromOSS(
  ossClient,
  process.env.OSS_bucket,
  "toubao/content",
  "download1111"
);
